package com.espirit.eap.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.ClassUtils;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.annotation.GenericType;
import com.googlecode.cswish.model.PageElement;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.struts.conversion.PageElementService;
import com.googlecode.cswish.util.ClassUtil;

@Service
public class EapImportService {

	@Resource
	private PageElementService pageElementService;
	
	private EapImport newEapImport(String modelName) {
		if (modelName == null) {
			modelName = ClassUtil.getRuntimeType(GenericType.MODEL);
		}
		EapImport eapImport;
		try {
			Class clazz = ClassUtils.getClass(modelName + "Import");
			eapImport = (EapImport) clazz.newInstance();
		} catch (Exception ex) {
			eapImport = new EapImport();
		}
		return eapImport;
	}
	
	// see StatGenericJPAService.importFile
	public List<String> getImportPropertyNames(String modelName) {
		if (modelName == null) {
			modelName = ClassUtil.getRuntimeType(GenericType.MODEL);
		}
		PageElements ps = pageElementService.getPageElements(modelName, "analyseImportFileColumns");
		if (ps != null) {
			PageElement pe = ps.findElementByType("importsetting");
			if (pe != null) {
				Collection<String> targetModelProperties = (Collection<String>)pe.getExtraParam("targetModelProperties");
				if (targetModelProperties != null && targetModelProperties.size() > 0) {
					List<String> ret = new ArrayList<String>(targetModelProperties);
					return ret;
				}
			}
		}
		
		EapImport eapImport = newEapImport(modelName);
		
		List<String> importPropertyNames = eapImport.getImportPropertyNames();
		if (importPropertyNames == null || importPropertyNames.size() == 0) {
			importPropertyNames = eapImport.getImportPropertyNames();
		}
		return importPropertyNames;
	}
	
	public List<String> getDefaultImportPropertyNames(String modelName) {
		EapImport eapImport = newEapImport(modelName);
		
		List<String> importPropertyNames = eapImport.getImportPropertyNames();
		if (importPropertyNames == null) {
			importPropertyNames = eapImport.getImportPropertyNames();
		}
		return importPropertyNames;
	}
}
